import axios from 'axios'
import { Notification, Message, MessageBox } from 'element-ui'
import store from '@/store'
// ↓此处代码并未提供
// import { getStore } from '@/utils/localStore'
// import { appCode } from '@/utils/config.js'
// import errorCode from '@/utils/errorCode'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  withCredentials: true,
  timeout: 10000
})

// request interceptor
service.interceptors.request.use(
  config => {
    // ↓此处代码先注释掉 因为目前的接口请求中不需要夹带token
    // const token = getStore(`${appCode}-token`)
    // config.headers.APPCLICATION_CODE = appCode
    // if (token) {
    //   config.headers.Authorization = 'Bearer ' + token
    // }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(res => {
  const code = res.data.code || 200
  // const message = errorCode[code] || res.data.message || errorCode.default
  const message = res.data.message;
  console.log(res)
  if (code === 401) {
    // 登录过期
    MessageBox.confirm(
      '登录状态已过期，您可以继续留在该页面，或者重新登录',
      '系统提示',
      {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      store.dispatch('LogOut').then(() => {
        location.reload()
      })
    })
  } else if (code === 500) {
    Message({
      message: message,
      type: 'error'
    })
    return Promise.reject(new Error(message))
  } else if (code !== 200) {
    Notification.error({
      title: message
    })
    // eslint-disable-next-line prefer-promise-reject-errors
    return Promise.reject('error')
  } else {
    return res.data
  }
},
error => {
  Message({
    message: error.message,
    type: 'error',
    duration: 1500
  })
  return Promise.reject(error)
}
)

export default service
